﻿using Admin.NET.Core.Service;
using Admin.NET.Application.Const;
using Admin.NET.Application.Entity;
using Microsoft.AspNetCore.Http;
using Magicodes.ExporterAndImporter.Excel;
using System.IO;
using Admin.NET.Application.Service.TopSdk;
using static SKIT.FlurlHttpClient.Wechat.Api.Models.CgibinMessageCustomSendRequest.Types;
namespace Admin.NET.Application;
/// <summary>
/// 校本选课服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class XuanKeService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<XuanKe> _rep; 
    private readonly SqlSugarRepository<JiaoxueBan> _jiaoxueBanRep;
    private readonly SqlSugarRepository<Teacher> _teacherRep;
    private readonly TopSdkService _topSdkService; 
    public XuanKeService(SqlSugarRepository<XuanKe> rep,
        SqlSugarRepository<JiaoxueBan> jiaoxueBanRep,
        SqlSugarRepository<Teacher> teacherRep,
        TopSdkService topSdkService)
    {
        _rep = rep;
        _topSdkService = topSdkService;
        _jiaoxueBanRep = jiaoxueBanRep;
        _teacherRep = teacherRep;
    }

    /// <summary>
    /// 分页查询校本选课
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    public async Task<SqlSugarPagedList<XuanKeOutput>> Page(XuanKeInput input)
    {
        var query = _rep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u =>
                u.Chengji.Contains(input.SearchKey.Trim())
                || u.Remark.Contains(input.SearchKey.Trim())
            )
            .WhereIF(input.XuankeTaskId>0, u => u.XuankeTaskId == input.XuankeTaskId)
            .WhereIF(input.BanjiId>0, u => u.BanjiId == input.BanjiId)
            .WhereIF(input.JiaoxueBanId>0, u => u.JiaoxueBanId == input.JiaoxueBanId)
            .WhereIF(input.StudentId>0, u => u.StudentId == input.StudentId)
            .WhereIF(input.KechengId>0, u => u.KechengId == input.KechengId)
            .WhereIF(!string.IsNullOrWhiteSpace(input.Chengji), u => u.Chengji.Contains(input.Chengji.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<XuankeTask>((u, xuanketaskid) => u.XuankeTaskId == xuanketaskid.Id )
            .LeftJoin<Banji>((u, xuanketaskid, banjiid) => u.BanjiId == banjiid.Id )
            .LeftJoin<JiaoxueBan>((u, xuanketaskid, banjiid, jiaoxuebanid) => u.JiaoxueBanId == jiaoxuebanid.Id )
            .LeftJoin<Student>((u, xuanketaskid, banjiid, jiaoxuebanid, studentid) => u.StudentId == studentid.Id )
            .LeftJoin<Kecheng>((u, xuanketaskid, banjiid, jiaoxuebanid, studentid, kechengid) => u.KechengId == kechengid.Id )
            .OrderBy((u, xuanketaskid, banjiid, jiaoxuebanid, studentid, kechengid) => studentid.Xh)
            .Select((u, xuanketaskid, banjiid, jiaoxuebanid, studentid, kechengid) => new XuanKeOutput
            {
                Id = u.Id,
                XuankeTaskId = u.XuankeTaskId, 
                XuankeTaskIdName = xuanketaskid.Name,
                BanjiId = u.BanjiId, 
                BanjiIdName = banjiid.Name,
                JiaoxueBanId = u.JiaoxueBanId, 
                JiaoxueBanIdName = jiaoxuebanid.Name,
                StudentId = u.StudentId, 
                StudentIdXh = studentid.Xh,
                StudentIdName = studentid.Name,
                KechengId = u.KechengId, 
                KechengIdName = kechengid.Name,
                IsYuxuan = u.IsYuxuan,
                Chengji = u.Chengji,
                Chuqin1 = u.Chuqin1,
                Chuqin2 = u.Chuqin2,
                Chuqin3 = u.Chuqin3,
                Chuqin4 = u.Chuqin4,
                Chuqin5 = u.Chuqin5,
                Chuqin6 = u.Chuqin6,
                Chuqin7 = u.Chuqin7,
                Chuqin8 = u.Chuqin8,
                Chuqin9 = u.Chuqin9,
                Chuqin10 = u.Chuqin10,
                Chuqin11 = u.Chuqin11,
                Chuqin12 = u.Chuqin12,
                Chuqin13 = u.Chuqin13,
                Chuqin14 = u.Chuqin14,
                Chuqin15 = u.Chuqin15,
                Chuqin16 = u.Chuqin16,
                Chuqin17 = u.Chuqin17,
                Chuqin18 = u.Chuqin18,
                Chuqin19 = u.Chuqin19,
                Chuqin20 = u.Chuqin20,
                Remark = u.Remark,
                CreateUserName = u.CreateUserName,
                UpdateUserName = u.UpdateUserName,
            });
        return await query.ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 增加校本选课
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    public async Task<long> Add(AddXuanKeInput input)
    {
        var entity = input.Adapt<XuanKe>();
        await _rep.InsertAsync(entity);
        return entity.Id;
    }

    /// <summary>
    /// 删除校本选课
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    public async Task Delete(DeleteXuanKeInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        //await _rep.FakeDeleteAsync(entity);   //假删除
        await _rep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 更新校本选课
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    public async Task Update(UpdateXuanKeInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);

        entity.KechengId = input.KechengId;
        entity.IsYuxuan = input.IsYuxuan;
        entity.Chengji = input.Chengji;
        entity.Remark = input.Remark;

        _rep.Update(entity);

        var list = await _rep.Context.Queryable<Kecheng>().Where(u => u.XuankeTaskId == input.XuankeTaskId).ToListAsync();
        foreach (var item in list)
        {
            item.LvquRenshu = await _rep.CountAsync(p => p.KechengId == item.Id);
            _rep.Context.Updateable(item).ExecuteCommand();
        }
    }

    /// <summary>
    /// 获取校本选课
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    public async Task<XuanKe> Detail([FromQuery] QueryByIdXuanKeInput input)
    {
        return await _rep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 导出学生
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Export"), NonUnify]
    [DisplayName("导出")]
    public async Task<IActionResult> Export(XuanKeInput input)
    {
        var list =await _rep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u =>
                u.Chengji.Contains(input.SearchKey.Trim())
                || u.Remark.Contains(input.SearchKey.Trim())
            )
            .WhereIF(input.XuankeTaskId > 0, u => u.XuankeTaskId == input.XuankeTaskId)
            .WhereIF(input.BanjiId > 0, u => u.BanjiId == input.BanjiId)
            .WhereIF(input.JiaoxueBanId > 0, u => u.JiaoxueBanId == input.JiaoxueBanId)
            .WhereIF(input.StudentId > 0, u => u.StudentId == input.StudentId)
            .WhereIF(input.KechengId > 0, u => u.KechengId == input.KechengId)
            .WhereIF(!string.IsNullOrWhiteSpace(input.Chengji), u => u.Chengji.Contains(input.Chengji.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Remark), u => u.Remark.Contains(input.Remark.Trim()))
            //处理外键和TreeSelector相关字段的连接
            .LeftJoin<XuankeTask>((u, xuanketaskid) => u.XuankeTaskId == xuanketaskid.Id)
            .LeftJoin<Banji>((u, xuanketaskid, banjiid) => u.BanjiId == banjiid.Id)
            .LeftJoin<JiaoxueBan>((u, xuanketaskid, banjiid, jiaoxuebanid) => u.JiaoxueBanId == jiaoxuebanid.Id)
            .LeftJoin<Student>((u, xuanketaskid, banjiid, jiaoxuebanid, studentid) => u.StudentId == studentid.Id)
            .LeftJoin<Kecheng>((u, xuanketaskid, banjiid, jiaoxuebanid, studentid, kechengid) => u.KechengId == kechengid.Id)
            .OrderBy(u => u.CreateTime)
            .Select((u, xuanketaskid, banjiid, jiaoxuebanid, studentid, kechengid) => new XuanKeExportDto
            {
                JiaoxueBanIdName = jiaoxuebanid.Name,
                StudentIdXh = studentid.Xh,
                StudentIdName = studentid.Name,
                KechengIdName = kechengid.Name,
                IsYuxuan = u.IsYuxuan,
                Chengji = u.Chengji,
            }).ToListAsync();

        IExcelExporter excelExporter = new ExcelExporter();
        var res = await excelExporter.ExportAsByteArray(list);
        return new FileStreamResult(new MemoryStream(res), "application/octet-stream") { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "选课信息汇总.xlsx" };
    }

    /// <summary>
    /// 获取选课任务列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "XuankeTaskXuankeTaskIdDropdown"), HttpGet]
    public async Task<dynamic> XuankeTaskXuankeTaskIdDropdown()
    {
        return await _rep.Context.Queryable<XuankeTask>()
                .Select(u => new
                {
                    Label = u.Name,
                    Value = u.Id
                }
                ).ToListAsync();
    }
    /// <summary>
    /// 获取班级列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "BanjiBanjiIdDropdown"), HttpGet]
    public async Task<dynamic> BanjiBanjiIdDropdown()
    {
        return await _rep.Context.Queryable<Banji>()
                .Select(u => new
                {
                    Label = u.Name,
                    Value = u.Id
                }
                ).ToListAsync();
    }
    /// <summary>
    /// 获取教学班列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "JiaoxueBanJiaoxueBanIdDropdown"), HttpGet]
    public async Task<dynamic> JiaoxueBanJiaoxueBanIdDropdown()
    {
        return await _rep.Context.Queryable<JiaoxueBan>()
                .Select(u => new
                {
                    Label = u.Name,
                    Value = u.Id
                }
                ).ToListAsync();
    }
    /// <summary>
    /// 获取学生列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "StudentStudentIdDropdown"), HttpGet]
    public async Task<dynamic> StudentStudentIdDropdown()
    {
        return await _rep.Context.Queryable<Student>()
                .Select(u => new
                {
                    Label = u.Name,
                    Value = u.Id
                }
                ).ToListAsync();
    }
    /// <summary>
    /// 获取课程列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "KechengKechengIdDropdown"), HttpGet]
    public async Task<dynamic> KechengKechengIdDropdown(long xuankeTaskId)
    {
        return await _rep.Context.Queryable<Kecheng>()
                .Where(u=>u.XuankeTaskId == xuankeTaskId)
                .Select(u => new
                {
                    Label = u.Name + "-" + u.LvquRenshu.Value.ToString() + "/" + u.ZhaoshengRenshu.ToString(),
                    Value = u.Id
                }
                ).ToListAsync();
    }




}

